﻿using CBS.APP;
using CBS.Desktop.FormPage;
using CBS.Model.ManageModel;
using CBS.Model.UIModel;
using CBS.Model.ViewModel;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CBS.Desktop.ViewPartial
{
    /// <summary>
    /// CoursePlanManage.xaml 的交互逻辑
    /// </summary>
    public partial class CoursePlanManage : UserControl
    {
        private Pagination pager = new() { rows = 10, page = 1, sidx = nameof(CoursePlanViewModel.CoursePlanId), sord = "desc" };
        private int loadState = 0;
        public CoursePlanManage()
        {
            InitializeComponent();

            LoadCondation();
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                // 调用处理方法
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
                e.Handled = true; // 如果需要，标记事件已处理
            }
        }
        private async void LoadCondation()
        {
            btn_Add.IsEnabled = false;
            btn_Search.IsEnabled = false;
            // 加载 ComboBox 数据
            await LoadDataAsync();

            // 查询 Grid 数据
            //FlushGrid();

            btn_Add.IsEnabled = true;
            btn_Search.IsEnabled = true;
        }

        private async Task LoadDataAsync()
        {
            // 使用 Task.WhenAll 等待所有 ComboBox 数据加载完成
            var tasks = new List<Task>
            {
                BindSemester(),
                BindGrade(),
                BindClass(),
                BindCourse()
            };

            await Task.WhenAll(tasks);
        }

        private async Task BindSemester()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => SemesterApp.GetSelectList());

                if (list.Count == 0)
                {
                    return;
                }


                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Semester.ItemsSource = list;
                }));
                cb_Semester.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async Task BindGrade()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => GradeApp.GetSelectList());

                list.Insert(0, new GradeViewModel { GradeId = 0, GradeName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Grade.ItemsSource = list;

                }));
                cb_Grade.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindClass()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => ClassApp.GetSelectList());

                list.Insert(0, new ClassViewModel { ClassId = 0, ClassName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Class.ItemsSource = list;

                }));
                cb_Class.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task BindCourse()
        {
            try
            {
                btn_Search.IsEnabled = false;
                var list = await Task.Run(() => CourseApp.GetSelectList());

                list.Insert(0, new CourseViewModel { CourseId = 0, CourseName = "全部" });

                this.Dispatcher.Invoke(new Action(() =>
                {
                    cb_Course.ItemsSource = list;


                })); 
                cb_Course.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void FlushGrid()
        {
            try
            {
                btn_Search.IsEnabled = false;
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                int gradeId = ((GradeViewModel)cb_Grade.SelectedItem).GradeId;
                int classId = ((ClassViewModel)cb_Class.SelectedItem).ClassId;
                int courseId = ((CourseViewModel)cb_Course.SelectedItem).CourseId;

                string key = tb_PlanName.Text.Trim();
                var data = await Task.Run(() => CoursePlanApp.GetList(pager, semesterId, gradeId, classId, courseId, key));

                this.Dispatcher.Invoke(() =>
                {
                    pg_DataList.MaxPageCount = pager.total;
                    dgr_DataList.ItemsSource = data;
                    btn_Search.IsEnabled = true;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void btn_Search_Click(object sender, RoutedEventArgs e)
        {
            pager.page = 1;
            pg_DataList.PageIndex = 1;
            FlushGrid();
        }

        private void btn_Add_Click(object sender, RoutedEventArgs e)
        {
            AddCoursePlan coursePlan = new()
            {
                Owner = Window.GetWindow(this)
            };
            var dialogResult = coursePlan.ShowDialog();
            if (dialogResult.HasValue && dialogResult.Value)
            {
                pager.page = 1;
                pg_DataList.PageIndex = 1;
                FlushGrid();
            }
        }

        private void btn_Delete_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                int semesterId = ((SemesterSelectModel)cb_Semester.SelectedItem).SemesterId;
                string key = tb_PlanName.Text.Trim();
                if (CoursePlanApp.IsCoursePlanUsed(semesterId, key))
                {
                    MessageBox.Show("");
                    return;
                }

                if (CoursePlanApp.BatchDeleteCoursePlan(semesterId, key))
                {
                    pager.page = 1;
                    pg_DataList.PageIndex = 1;
                    FlushGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void Pg_DataList_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            pager.page = e.Info;
            FlushGrid();
        }

        private void dg_Delete(object sender, RoutedEventArgs e)
        {
            try
            {
                var tmp = sender as System.Windows.Controls.Button;
                var data = tmp.DataContext as CoursePlanViewModel;
                if (CoursePlanApp.IsCoursePlanUsed(data.CoursePlanId))
                {
                    MessageBox.Show("数据已经被使用，不能删除。","删除失败",MessageBoxButton.OK,MessageBoxImage.Stop);
                    return;
                }
                if (CoursePlanApp.DeleteCoursePlan(data.CoursePlanId))
                {
                    FlushGrid();
                }
                else
                {

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private void dg_Edit(object sender, RoutedEventArgs e)
        {
            try
            {
                var tmp = sender as System.Windows.Controls.Button;
                var data = tmp.DataContext as CoursePlanViewModel;
                EditCoursePlanModel model = new()
                {
                    CoursePlanId = data.CoursePlanId,
                    CoursePlanName = data.CoursePlanName,
                    TeacherId = data.TeacherId,
                    ClassId = data.ClassId,
                    ClassTimeLong = data.ClassTimeLong,
                    CourseCount = data.CourseCount,
                    CourseId = data.CourseId,
                    CoursePrice = data.CoursePrice,
                    GradeId = data.GradeId,
                    Memo = data.Memo,
                    PlanNum = data.PlanNum,
                    SemesterId = data.SemesterId,

                };

                EditCoursePlan coursePlan = new(model)
                {
                    Owner = Window.GetWindow(this)
                };
                var dialogResult = coursePlan.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    FlushGrid();
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(Window.GetWindow(this), ex.Message, "发生错误！", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

    }
}
